//
//  ACDeviceSettingViewCell.m
//  MonitoringSystem
//
//  Created by JiaKang.Zhong on 16/4/28.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "ACDeviceSettingViewCell.h"
#import "ACUserLoginManage.h"
@interface ACDeviceSettingViewCell ()<ACCircleViewForCallBackPort>{
    NSInteger newPortColorTag; // 新的颜色标记
    NSInteger oldPortColorTag; // 旧的颜色标记
}
/*
 几种颜色的端口
 */
@property (weak, nonatomic) IBOutlet UIButton *btnRed;
@property (weak, nonatomic) IBOutlet UIButton *btnGreen;
@property (weak, nonatomic) IBOutlet UIButton *btnYellow;
@property (weak, nonatomic) IBOutlet UIButton *btnBlue;// 居中那个
@property (weak, nonatomic) IBOutlet UIButton *btnGray;
@property (weak, nonatomic) IBOutlet UIButton *btnBlack;
@property (weak, nonatomic) IBOutlet UIButton *btnClose;
/**
 *   约束部分
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *redAndGreenConstrain;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *greenAndYellowConstrain;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *yellowAndBlueConstrain;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *grayAndBlueConstrain;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *blackAndGrayConstrain;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *clsoeAndBlackConstrain;
@property (weak, nonatomic) IBOutlet UIImageView *imgDeviceLayer; // 头部的3d图形
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgDeviceLayerHeightConstraint; // 高度约束
@property(nonatomic,strong) NSMutableArray* portBtnArr; // 端口颜色的数组集合
@property (weak, nonatomic)  UIButton *recommedBtn; // 推荐配置按钮
- (IBAction)showRecommodCallBack:(id)sender;

@end
@implementation ACDeviceSettingViewCell

- (NSMutableArray *)portBtnArr{
    if (!_portBtnArr) {
        _portBtnArr = [NSMutableArray array];
    }
    return _portBtnArr;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    
    self.recommedBtn.tag = 110;
   
    /*   初始化数据   */
    [self initData];
    /*   约束   */
    [self configConstraints];
    /*   增加端口   */
    [self setUpSmartPortViewForRotateCircle];
    
}



#pragma mark ****************** 初始化值 ******************
- (void) initData{
    self.btnRed.tag = PORTREDCOLOR;
    self.btnGreen.tag = PORTGREENCOLOR;
    self.btnYellow.tag = PORTYELLOWCOLOR;
    self.btnBlue.tag = PORTBLUECOLOR;
    self.btnGray.tag = PORTGRAYCOLOR;
    self.btnBlack.tag = PORTBLACKCOLOR;
    self.btnClose.tag = PORTKNOWNCOLOR;
    [self.portBtnArr addObject:self.btnRed];
    [self.portBtnArr addObject:self.btnGreen];
    [self.portBtnArr addObject:self.btnYellow];
    [self.portBtnArr addObject:self.btnBlue];
    [self.portBtnArr addObject:self.btnGray];
    [self.portBtnArr addObject:self.btnBlack];
    [self.portBtnArr addObject:self.btnClose];
    for (UIButton * tempBtn in self.portBtnArr) {
        [tempBtn setTitle:@"0" forState:UIControlStateNormal];
    }
}


#pragma mark ****************** 增加约束 ******************
- (void) configConstraints{
    
    if(SCREEN_HEIGHT == 480){
        //3.5 废弃
    }else if(SCREEN_HEIGHT == 568){ //4.0
    }
    else if(SCREEN_HEIGHT == 667){ // 4.7
        self.redAndGreenConstrain.constant = self.redAndGreenConstrain.constant + 5;
        self.greenAndYellowConstrain.constant = self.greenAndYellowConstrain.constant + 5;
        self.yellowAndBlueConstrain.constant = self.yellowAndBlueConstrain.constant + 5;
        self.grayAndBlueConstrain.constant = self.grayAndBlueConstrain.constant + 5;
        self.blackAndGrayConstrain.constant = self.blackAndGrayConstrain.constant + 5;
        self.clsoeAndBlackConstrain.constant = self.clsoeAndBlackConstrain.constant + 5;
    }else if(SCREEN_HEIGHT == 736){ //5.5
        self.redAndGreenConstrain.constant = self.redAndGreenConstrain.constant + 10;
        self.greenAndYellowConstrain.constant = self.greenAndYellowConstrain.constant + 10;
        self.yellowAndBlueConstrain.constant = self.yellowAndBlueConstrain.constant + 10;
        self.grayAndBlueConstrain.constant = self.grayAndBlueConstrain.constant + 10;
        self.blackAndGrayConstrain.constant = self.blackAndGrayConstrain.constant + 10;
        self.clsoeAndBlackConstrain.constant = self.clsoeAndBlackConstrain.constant + 10;
        self.imgDeviceLayerHeightConstraint.constant = self.imgDeviceLayerHeightConstraint.constant + 20;
    }
}

- (void)setIsEmploy:(BOOL)isEmploy{
    self.circleView.isEmploy = isEmploy;
    self.circleView.employ = self.employ;
    self.circleView.zone = self.zone;
}


#pragma mark ****************** 添加端口 ******************
-(void) setUpSmartPortViewForRotateCircle{
    //  转盘中心
    ACCircleView* rotateViewBG = [[ACCircleView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 150)];
    rotateViewBG.circleViewDelegate = self;
    rotateViewBG.cirCollectionView = self.collectionView;
    [self.contentView addSubview:rotateViewBG];
    self.circleView = rotateViewBG;
   
}


#pragma mark 翻滚层的时候调用
- (void)setUpWith:(UICollectionView *)collection andIndex:(NSInteger)currIndex andPortLayer:(NSInteger ) portLayer{

    self.collectionView = collection;
    self.currIndex = currIndex;
    self.portLayer = portLayer;
    /*    设置泵芯层级的图片   */
    self.imgDeviceLayer.image = [UIImage imageNamed:[NSString stringWithFormat:@"paixin-%d-%d",(int)(portLayer),(int)(currIndex + 1)]];
    /*    给转盘设置旋转角度  */
    self.circleView.currLayer = currIndex;
    /*   设置当前层的端口信息  如果服务器中有数据，给转盘设定原来的配置数据  */
    [self configExitPortInformationAndShow:currIndex];
    
    [self.circleView calcalatePortOutPut:-1];
}



#pragma mark 配置已经存在的端口信息
/**
 *  并且显示出来,设置每一个页面的配置信息
 *  @param currentLayer 当前层的数据传过去就好了
 */
- (void)configExitPortInformationAndShow:(NSInteger) currentLayer{
    
    int layer = -1;
    int pos = -1;
    int portColorIndex = -1;
    NSDictionary * dicArr =  [UD objectForKey:[NSString stringWithFormat:@"%@-%@",PORTDIC,[ACUserLoginManage shareInstance].userName]];
    if (dicArr) {
        // key是位置（层,第几个），value是颜色
        NSArray * portPos =  [dicArr allKeys];
        NSArray * portColor = [dicArr allValues];
        for ( int index = 0;  index < portPos.count; index++){
            NSString * keyStr = portPos[index];
            // 层
            layer = [[keyStr substringToIndex:1] intValue];
            pos = [[keyStr substringFromIndex:1] intValue];
            portColorIndex =  [portColor[index] intValue];
            if (currentLayer == layer) {
                [self.circleView configCurrentInformationWithPos:pos andColorTag:portColorIndex andCurrLayer:currentLayer andIndexLayer:layer];
            }
        }
    }
    // 设置颜色端口总数
    NSDictionary * tempDic =  [UD objectForKey:[NSString stringWithFormat:@"%@-%@",PORTCOLORTAGCOUNT,[ACUserLoginManage shareInstance].userName]];
    for (NSString * keys in tempDic.allKeys) {
        UIButton * tempBtn =   [self getButtonWithColorTag:[keys  integerValue]];
        [tempBtn setTitle:[NSString stringWithFormat:@"%d",[[tempDic objectForKey:keys] intValue]] forState:UIControlStateNormal];
    }
}


#pragma mark  ********************** 从服务器中获取到最新的数据 **********************
/*
    1.设置对应端口上的颜色
    2.计算底部的端口颜色总数
*/
- (void)setConfigData:(NSArray *)configData{
    // 计算颜色总数，先清空数据
    NSMutableDictionary * dicMTemp = [NSMutableDictionary dictionary];
    for (UIButton * tempBtn in self.portBtnArr) {
        [tempBtn setTitle:@"0" forState:UIControlStateNormal];
         [dicMTemp setObject:[NSString stringWithFormat:@"%@",tempBtn.currentTitle] forKey:[NSString stringWithFormat:@"%d",(int)tempBtn.tag]];
    }
    [UD setObject:dicMTemp forKey:[NSString stringWithFormat:@"%@-%@",PORTCOLORTAGCOUNT,[ACUserLoginManage shareInstance].userName] ];
    [UD synchronize]; // 刷新数据
    [UD setObject:nil forKey:[NSString stringWithFormat:@"%@-%@",PORTDIC,[ACUserLoginManage shareInstance].userName]];
    NSMutableDictionary * dicArr = [NSMutableDictionary dictionary];
    for (NSString * tempStr in configData) {
        NSRange _range =  [tempStr rangeOfString:@"-"];
        int layer = [[tempStr substringToIndex:1] intValue];// 获取层
        int pos = [[tempStr substringWithRange:NSMakeRange(1, _range.location)] intValue];
        int colorTag = [[tempStr substringWithRange:NSMakeRange((_range.location + _range.length), tempStr.length - (_range.location + _range.length))] intValue];
        /*
            1、如果是第一层，那么就直接先显示出来
            2、给所有的端口控件设置上colorTag标记(颜色来标记)。用以后续的计算
         */
        if (layer == 0) {
           [self.circleView configCurrentInformationWithPos:pos andColorTag:colorTag andCurrLayer:-1 andIndexLayer:-1];
        }
        // 保存起来 plist文件中--------第二层后的获取从plist文件拿
        NSString * identifter = [NSString stringWithFormat:@"%d%d",layer,pos ];
        [dicArr setObject:@(colorTag) forKey:identifter];
       
        // 修改对应颜色端口的 颜色总数
        UIButton * tempBtn =  [self getButtonWithColorTag:colorTag];// 取出对应的按钮
        [tempBtn setTitle:[NSString stringWithFormat:@"%d",(int)([tempBtn.currentTitle integerValue] + 1)] forState:UIControlStateNormal];
    }
    [UD setObject:[dicArr copy] forKey:[NSString stringWithFormat:@"%@-%@",PORTDIC,[ACUserLoginManage shareInstance].userName]];
    [UD synchronize];
    // 计算颜色总数
    NSMutableDictionary * dicM = [NSMutableDictionary dictionary];
    for (UIButton * tempBtn in self.portBtnArr) {
          [dicM setObject:[NSString stringWithFormat:@"%@",tempBtn.currentTitle] forKey:[NSString stringWithFormat:@"%d",(int)tempBtn.tag]];
    }
    [UD setObject:dicM forKey:[NSString stringWithFormat:@"%@-%@",PORTCOLORTAGCOUNT,[ACUserLoginManage shareInstance].userName] ];
    [UD synchronize];
    NSLog(@"查看设定的颜色 ：%@",[UD objectForKey:[NSString stringWithFormat:@"%@-%@",PORTCOLORTAGCOUNT,[ACUserLoginManage shareInstance].userName]]);
    
    [self.circleView calcalatePortOutPut:-1];
}



#pragma mark             ##############   ACCircleView的 delegate   ###################
/**
 *  设定颜色成功.保存数据到本地，然后设定颜色，修改颜色的对应的个数。
    index（值范围 1~ 12）   位置
    layer（值范围 1~。。。） 层
    tag(颜色标记)           新的颜色
    oldColorTag            原来的颜色标记
 */
- (void) portCallBackIndex:(NSInteger )index andLayer:(NSInteger) layer andTag:(NSInteger)tag andOldColorTag:(NSInteger)oldColorTag {
    
    NSLog(@"当前被触摸中的按钮的层级是：%d,取数组下标为：%d的元素，新的颜色下标是 %d 原来的下标是:%d",(int)layer,(int)index, (int)tag,(int)oldColorTag);
    // 相同颜色的不处理
    if (tag == oldColorTag) {
        return;
    }
    /*    写入本地保存  */
    NSString * identifter = [NSString stringWithFormat:@"%d%d",(int)layer,(int)index ];
    NSMutableDictionary * dicArr = [[UD objectForKey:[NSString stringWithFormat:@"%@-%@",PORTDIC,[ACUserLoginManage shareInstance].userName]] mutableCopy];
    if (!dicArr) {
        dicArr = [NSMutableDictionary dictionary];
    }
    [dicArr setObject:@(tag) forKey:identifter];
    [UD setObject:[dicArr copy] forKey:[NSString stringWithFormat:@"%@-%@",PORTDIC,[ACUserLoginManage shareInstance].userName]];
    /*    写入端口颜色总数      */
    [self updatePortBtnCountWithBtn:[self getButtonWithColorTag:tag] andOldButton:[self getButtonWithColorTag:oldColorTag]];
    // 修改端口数
    [self.circleView calcalatePortOutPut:-1];
}



// 根据颜色标记来获取对应的按钮
- (UIButton *) getButtonWithColorTag:(NSInteger)colorTag{
    switch (colorTag) {
        case PORTREDCOLOR:{
            // 红
            return self.btnRed;
        }
            break;
        case PORTGREENCOLOR:{
            // 绿
            return self.btnGreen;
        }
            break;
        case PORTYELLOWCOLOR:{
            // 黄
            return self.btnYellow;
        }
            break;
        case PORTBLUECOLOR:{
            // 蓝
            return self.btnBlue;
        }
            break;
        case PORTGRAYCOLOR:{
            //灰
            return self.btnGray;
        }
            break;
        case PORTBLACKCOLOR:{
            //黑
            return self.btnBlack;
        }
            break;
        case PORTKNOWNCOLOR:{
            // 关闭
            return self.btnClose;
        }
            break;
        default:
            break;
    }
    return nil;
}

// 更新按钮上的数值
- (void) updatePortBtnCountWithBtn:(UIButton *)newBtn andOldButton:(UIButton *) oldBtn {
    
    [ oldBtn setTitle:[NSString stringWithFormat:@"%d",(int)[oldBtn.currentTitle integerValue] - 1] forState:UIControlStateNormal];
    [ newBtn setTitle:[NSString stringWithFormat:@"%d",(int)[newBtn.currentTitle integerValue] + 1] forState:UIControlStateNormal];
      NSLog(@"oldBtn:%@ newBtn:%@",oldBtn.currentTitle,newBtn.currentTitle);
    /*    修改端口总数  */
    NSMutableDictionary * dicM = [NSMutableDictionary dictionary];
    for (UIButton * temp in self.portBtnArr) {
        // 值     ---------    颜色
        [dicM setObject:@([temp.currentTitle integerValue]) forKey:[NSString stringWithFormat:@"%d",(int)temp.tag]];
    }
    [UD setObject:dicM forKey:[NSString stringWithFormat:@"%@-%@",PORTCOLORTAGCOUNT,[ACUserLoginManage shareInstance].userName] ];
    [UD synchronize];
    NSLog(@"查看设定的颜色 ：%@",[UD objectForKey:[NSString stringWithFormat:@"%@-%@",PORTCOLORTAGCOUNT,[ACUserLoginManage shareInstance].userName]]);
}

- (NSString *)getViewWithImageName:(PORTCOLOR) TAG{
    
    if(TAG == PORTREDCOLOR){return @"Round-red";}
    else if (TAG == PORTGREENCOLOR){return @"Round-green";}
    else if (TAG == PORTYELLOWCOLOR){return @"Round-yellow";}
    else if (TAG == PORTBLUECOLOR){return @"Round-blue";}
    else if (TAG == PORTGRAYCOLOR){return @"Round-lightgrey";}
    else if (TAG == PORTBLACKCOLOR){return @"Round-black";}
    else if(TAG == PORTKNOWNCOLOR) {return @"Round-noCount";}
    else
        return @"device_whiteCircle";
}


#pragma mark -------------- 推荐配置 --------------
- (IBAction)showRecommodCallBack:(id)sender {
    
    if ([self.delegate respondsToSelector:@selector(showRecommedCallBack)]) {
        [self.delegate showRecommedCallBack];
    }
}


- (void) openSelectPortMaskLayerForGuid4{
    
    [self.circleView openSelectPortMaskLayerForGuid4];
}
@end
